#include "tdialoglogin.h"
#include "ui_tdialoglogin.h"
#include <QPainter>
#include <QSettings>
#include <QCryptographicHash>
#include <QMessageBox>
#include <QColor>

// 构造函数：初始化所有功能
tDialogLogin::tDialogLogin(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::tDialogLogin)
{
    ui->setupUi(this);
    initStyle();          // 初始化界面样式
    initBackground();     // 初始化动态渐变背景
    readSettings();       // 读取加密的用户信息
    ui->lineEdit_2->setEchoMode(QLineEdit::Password); // 密码不可见
    this->setAttribute(Qt::WA_DeleteOnClose);         // 关闭即删除
    this->setWindowTitle("登录 - 窗口监控系统");       // 设置窗口标题

    // 手动关联取消按钮的点击信号
    connect(ui->pushButton_2_click, &QPushButton::clicked, this, &tDialogLogin::on_pushButton_2_clicked);
}

// 析构函数：释放资源
tDialogLogin::~tDialogLogin()
{
    delete m_timeLine;    // 释放 QTimeLine
    delete m_scene;
    delete ui;
}

// 初始化界面样式
void tDialogLogin::initStyle()
{
    // 窗口无边框+圆角
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);
    this->setStyleSheet(R"(
        QDialog {
            border-radius: 10px;
            background: transparent;
        }
        QLineEdit {
            height: 35px;
            border: 1px solid #E5E5E5;
            border-radius: 17px;
            padding-left: 15px;
            font-size: 14px;
            background: rgba(255,255,255,0.9);
        }
        QLineEdit:focus {
            border-color: #4A90E2;
            outline: none;
        }
        QPushButton {
            height: 35px;
            border-radius: 17px;
            font-size: 14px;
        }
        QPushButton#pushButton {
            background: #4A90E2;
            color: white;
            border: none;
        }
        QPushButton#pushButton:hover {
            background: #3A80D2;
        }
        QPushButton#pushButton_2_click {
            background: #F5F5F5;
            color: #333;
            border: 1px solid #E5E5E5;
        }
        QPushButton#pushButton_2_click:hover {
            background: #EAEAEA;
        }
        QCheckBox {
            font-size: 13px;
            color: #666;
            margin: 8px 0;
        }
    )");
}

// 初始化动态渐变+图片背景
void tDialogLogin::initBackground()
{
    // 1. 加载背景图片（降低透明度，突出渐变）
    QPixmap bgPixmap(":/picture/OIP-C.png");
    if (bgPixmap.isNull()) {
        qWarning() << "背景图片加载失败，使用默认纯色";
        bgPixmap = QPixmap(375, 275);
        bgPixmap.fill(Qt::transparent); // 完全透明，不影响渐变
    }

    // 2. 初始化渐变（强对比起始色）
    QPointF startPoint(0, 0);
    QPointF endPoint(this->width(), this->height());
    m_currentGradient = QLinearGradient(startPoint, endPoint);
    m_currentGradient.setColorAt(0, QColor(0, 150, 255, 255));    // 亮蓝色（不透明）
    m_currentGradient.setColorAt(1, QColor(255, 50, 150, 255));   // 亮粉色（不透明）

    // 3. 动画速度提升（3秒循环，变化更快）
    m_timeLine = new QTimeLine(3000, this);  // 3秒完成一次渐变循环
    m_timeLine->setFrameRange(0, 60);        // 减少帧数，让变化更显著
    m_timeLine->setLoopCount(-1);
    connect(m_timeLine, &QTimeLine::frameChanged, this, &tDialogLogin::updateGradient);
    m_timeLine->start();

    // 4. 背景图片几乎透明，不遮挡渐变
    m_scene = new QGraphicsScene(this);
    m_bgItem = new QGraphicsPixmapItem(bgPixmap.scaled(this->size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
    m_bgItem->setOpacity(0.05);  // 几乎透明，仅保留极淡纹理
    m_scene->addItem(m_bgItem);
}

// 更新渐变颜色（肉眼可见的强变化）
void tDialogLogin::updateGradient(int frame)
{
    // 计算进度（0.0-1.0）
    qreal progress = frame / 60.0;  // 适配60帧，变化更剧烈

    // 超广色域变化：从红色→绿色→蓝色→紫色（完整色相环循环）
    qreal hue1 = fmod(progress, 1.0);           // 0.0(红) → 1.0(红)
    qreal hue2 = fmod(progress + 0.5, 1.0);     // 互补色（对比更强）

    // 最高饱和度和亮度（颜色最鲜艳）
    QColor color1 = QColor::fromHsvF(hue1, 1.0, 1.0, 1.0);  // 饱和度100%，亮度100%
    QColor color2 = QColor::fromHsvF(hue2, 1.0, 1.0, 1.0);  // 完全不透明

    // 渐变方向剧烈变化（从左上角→右下角 到 右上角→左下角）
    QPointF newStart(
        progress < 0.5 ? 0 : this->width(),  // 左右端点切换
        progress < 0.5 ? 0 : this->height()
        );
    QPointF newEnd(
        progress < 0.5 ? this->width() : 0,  // 反向切换
        progress < 0.5 ? this->height() : 0
        );

    // 应用新渐变（强制刷新）
    m_currentGradient = QLinearGradient(newStart, newEnd);
    m_currentGradient.setColorAt(0, color1);
    m_currentGradient.setColorAt(1, color2);
    // 增加中间色，让渐变层次更丰富
    m_currentGradient.setColorAt(0.5, QColor::fromHsvF(fmod(progress+0.25,1.0), 1.0, 1.0));

    update(); // 立即重绘
}

// 绘图事件：强化渐变显示
void tDialogLogin::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);  // 抗锯齿让渐变更平滑

    // 1. 绘制渐变背景（覆盖整个窗口）
    painter.setBrush(m_currentGradient);
    painter.drawRect(this->rect());

    // 2. 绘制极淡背景图片（不影响渐变）
    if (m_bgItem) {
        painter.drawPixmap(this->rect(), m_bgItem->pixmap());
    }

    QDialog::paintEvent(event);
}

// 窗口大小变化时更新背景
void tDialogLogin::resizeEvent(QResizeEvent *event)
{
    QDialog::resizeEvent(event);
    if (m_bgItem) {
        m_bgItem->setPixmap(m_bgItem->pixmap().scaled(event->size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
    }

    // 重新设置渐变以适应新窗口大小
    QPointF newStart(0, 0);
    QPointF newEnd(event->size().width(), event->size().height());
    m_currentGradient = QLinearGradient(newStart, newEnd);
    m_currentGradient.setColorAt(0, QColor(0, 150, 255, 255));
    m_currentGradient.setColorAt(1, QColor(255, 50, 150, 255));
}

// 以下函数保持不变...
QString tDialogLogin::encrypt(QString pw)
{
    QCryptographicHash hash(QCryptographicHash::Md5);
    hash.addData(pw.toLocal8Bit());
    return hash.result().toHex();
}

void tDialogLogin::readSettings()
{
    QSettings settings("WWB-QT", "Monitor_System");
    m_isSaveInfo = settings.value("SaveInfo", false).toBool();
    m_user = settings.value("Username", "user").toString();
    QString defaultPswd = encrypt("123456");
    m_pswd = settings.value("Password", defaultPswd).toString();

    if (m_isSaveInfo) {
        ui->lineEdit->setText(m_user);
        ui->checkBox->setChecked(true);
    }
}

void tDialogLogin::writeSettings()
{
    QSettings settings("WWB-QT", "Monitor_System");
    settings.setValue("SaveInfo", m_isSaveInfo);
    settings.setValue("Username", m_user);
    settings.setValue("Password", m_pswd);
}

void tDialogLogin::on_pushButton_clicked()
{
    QString inputUser = ui->lineEdit->text().trimmed();
    QString inputPswd = ui->lineEdit_2->text().trimmed();
    QString encryptInputPswd = encrypt(inputPswd);

    if (inputUser == m_user && encryptInputPswd == m_pswd) {
        m_user = inputUser;
        m_pswd = encryptInputPswd;
        writeSettings();
        QMessageBox::information(this, "成功", "登录成功！");
        this->accept();
    } else {
        m_tryCount++;
        if (m_tryCount >= 3) {
            QMessageBox::critical(this, "错误", "输入错误次数过多，程序即将退出！");
            this->reject();
        } else {
            QMessageBox::warning(this, "错误", QString("用户名或密码错误，还有 %1 次机会").arg(3 - m_tryCount));
        }
    }
}

void tDialogLogin::on_pushButton_2_clicked()
{
    this->reject();
}

void tDialogLogin::on_checkBox_stateChanged(int arg1)
{
    m_isSaveInfo = (arg1 == Qt::Checked);
}

void tDialogLogin::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_moving = true;
        m_lastpos = event->globalPosition().toPoint() - this->pos();
    }
    QDialog::mousePressEvent(event);
}

void tDialogLogin::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_moving = false;
    }
    QDialog::mouseReleaseEvent(event);
}

void tDialogLogin::mouseMoveEvent(QMouseEvent *event)
{
    if (m_moving && (event->buttons() & Qt::LeftButton)) {
        QPoint currentPos = event->globalPosition().toPoint();
        this->move(currentPos - m_lastpos);
    }
    QDialog::mouseMoveEvent(event);
}
